<template>
    <div>
        <!-- 图片上传 -->
        <div v-if="uploadType === 'jpeg' || uploadType === 'jpg' || uploadType === 'png' || uploadType === 'JPEG' || uploadType === 'JPG' || uploadType === 'PNG'">
            <!-- 自定义上传  -->
            <el-upload
                ref="upImg"
                class="avatar-uploader fl"
                action="#"
                list-type="picture-card"
                :limit="uploadData.uploadImgLimit"
                :http-request="uploadOperate"
                :file-list="uploadData.fileList"
                :on-exceed="handleExceed"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :before-upload="beforeAvatarUpload"
                :class="{hide:hideUpload}"
                >
                <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-dialog :visible.sync="uploadData.dialogVisible">
                <img width="100%" :src="uploadData.dialogImageUrl" alt="">
            </el-dialog>
        </div>
        <!-- 文件上传 -->
        <!-- 视频上传 -->
        <div v-if="uploadType ==='file' || uploadType ==='FILE' || uploadType === 'video' || uploadType === 'VIDEO' || uploadType === 'audio' || uploadType === 'Audio'" class="fl">
            <el-upload
                class="upload-demo"
                action="#"
                :limit="uploadData.uploadImgLimit"
                :http-request="uploadOperate"
                :file-list="uploadData.fileList"
                :on-exceed="handleExceed"
                :on-preview="handlePictureCardPreview"
                :before-remove="beforeRemove"
                :on-remove="handleRemove"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :before-upload="beforeAvatarUpload"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">上传资源不超{{uploadData.size}}MB</div>
            </el-upload>
            <div v-if='showVideo'>
            <div class='fl mr10' v-for='(item,index) in list' :key='index'>
                <video controls  class='avatar mt10 mr10' :src="item.videoUrl">
                </video>
            </div>
            </div>
            <div class='mt10' v-show='showAudio'>
                <audio :src="audioSrc" ref='audioref' controls></audio>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: 'EleUpload',
    props: {
        uploadData: {
            type: Object,
            default: () =>{}
        }
    },
    data() {
        return {
            imageUrl: '',
            hideUpload: false,
            uploadType: 'jpeg',
            fileMaxNum: 1,
            videoUrl:'',
            audioSrc:'',
            showAudio:false,
            showVideo: false,
            list: [],
            num: 0
        };
    },
    mounted() {
        this.hideUpload = this.uploadData.hideUpload ? this.uploadData.hideUpload : false
        this.uploadType = this.uploadData.type ? this.uploadData.type : "jpeg"
    },
    methods: {
        uploadOperate(data) {
            const uploadType = this.uploadType
            let _this = this
            let params = new FormData()
            params.append('file', data.file)
            console.log(data)
            new Promise((resolve,reject)=>{
                _this.$emit('beforeUploadHandle',params)
                resolve(params)
            }).then((params) => {
                console.log(params)
                let apiName = _this.uploadData.apiName
                apiName(params).then(response => {
                    //假数据
                    response={"retCode":"0000000","retDesc":"操作成功!","timestamp":"2020-11-24 12:36:12.626","rspBody":{"fileExtension":"mp4","originalFileName":"video.mp4","fileRelativePath":"group1/M00/00/01/CgP3-l-8jhqAblRbACNnq7zN20c969.mp4","fileAbsolutePath":"http://10.3.247.250:88/group1/M00/00/01/CgP3-l-8jhqAblRbACNnq7zN20c969.mp4","uploadTime":"2020-11-24 12:36:19","fileSize":2320299,"base64Data":null,"fastDfsGroup":"group1","storeMode":"2","videoDuration":null,"videoFormat":null,"fileSid":516,"templateCode":null,"templateSid":null,"fileBrowsePath":null}}
                    // response={"retCode":"0000000","retDesc":"操作成功!","timestamp":"2020-11-24 13:25:58.719","rspBody":{"fileExtension":"mp3","originalFileName":"孔艺 - 韭菜花 (伴奏).mp3","fileRelativePath":"group1/M00/00/02/CgP3-l-8mceAJCVJADyi1X5ouBE899.mp3","fileAbsolutePath":"http://10.3.247.250:88/group1/M00/00/02/CgP3-l-8mceAJCVJADyi1X5ouBE899.mp3","uploadTime":"2020-11-24 13:26:08","fileSize":3973845,"base64Data":null,"fastDfsGroup":"group1","storeMode":"2","videoDuration":null,"videoFormat":null,"fileSid":518,"templateCode":null,"templateSid":null,"fileBrowsePath":null}}
                    let _data = response.rspBody;
                    if(uploadType === 'jpeg' || uploadType === 'jpg' || uploadType === 'png' || uploadType === 'JPEG' || uploadType === 'JPG' || uploadType === 'PNG'){
                        let uploadImgLimit = _this.uploadData.uploadImgLimit ? _this.uploadData.uploadImgLimit : 1
                        if(_this.fileMaxNum < uploadImgLimit) {
                            _this.hideUpload = false
                        }else {
                            _this.hideUpload = true
                        }
                        _this.fileMaxNum ++
                    }
                    if(uploadType === 'video' || uploadType === 'VIDEO'){
                        _this.showVideo = true
                        // debugger
                        _this.videoUrl = _data.fileAbsolutePath
                        _data.videoUrl = _data.fileAbsolutePath
                        _data.uid = data.file.uid
                        _this.list.push(response.rspBody)
                        console.log(_this.list)
                    }
                    if(uploadType == 'audio' || uploadType == 'AUDIO') {
                        console.log(_this.$refs.audioref)
                        this.showAudio = true
                        this.audioSrc = _data.fileAbsolutePath
                    }
                    _this.$emit('uploadSuccessCallback', response)
                })
            })
        },
        beforeAvatarUpload(file) { // 文件上传之前调用做一些拦截限制
            // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            // if (!isJPG) {
            // this.$message.error('上传头像图片只能是 JPG | PNG 格式!');
            // }
            //是否要限制上传的图片格式？待完善
            const uploadType = this.uploadType
            if(uploadType === 'video' || uploadType === 'VIDEO'){
                if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) == -1) {
                    this.$message.error("请上传正确的视频格式");
                    return false;
                }
            }
            //限制文件大小
            const size = this.uploadData.size ? this.uploadData.size : 50;
            const isLt2M = file.size / 1024 / 1024 < size;
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 '+ size +'MB!');
            }
            // return isJPG && isLt2M;
            return isLt2M
        },
        uploadError() {

        },
        uploadSuccess(response, file, fileList) { //on-success	文件上传成功时的钩子  这里uploadOperate覆盖
            console.log('上传成功')
            // debugger
            let uploadImgLimit = this.uploadData.uploadImgLimit ? this.uploadData.uploadImgLimit : 1
            if(fileList.length < uploadImgLimit) {
                this.hideUpload = false
            }else {
                this.hideUpload = true
            }

            this.$emit('uploadSuccessCallback', file)
        },

        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        handleRemove(file, fileList) {
            if(this.uploadType === 'video' || this.uploadType === 'VIDEO') {
                for(let i=0;i<this.list.length;i++){
                    if(this.list[i].uid == file.uid) {
                        this.list.splice(i,1)
                    }
                }
                console.log(this.list)
            }
            this.hideUpload = false
        },
        uploadChange(file, fileList) {
            this.hideUpload = fileList.length >= this.uploadImgLimit
        },
        handlePictureCardPreview(file) { //点击文件列表中已上传的文件时的钩子
            this.uploadData.dialogImageUrl = file.url;
            this.uploadData.dialogVisible = true;
        },
        handleExceed(files, fileList) { // 图片上传超过数量限制
            this.$message.warning('上传数量不能超过'+this.uploadData.uploadImgLimit+'个资源!')
        },
        uploadError(err, file, fileList) { // 图片上传失败调用
            this.$message.error('上传失败!')
        }
    }
}
</script>
<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 148px;
        height: 148px;
        line-height: 148px;
        text-align: center;
    }
    .avatar {
        width: 148px;
        height: 148px;
        display: block;
    }
    /deep/ .hide .el-upload--picture-card{
        display:none;
    }
</style>
